package org.ligson.fwc.api.dto;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.ligson.fwc.api.enums.BaseErrorCode;
import org.ligson.fwc.api.util.JsonUtil;
import org.ligson.fwc.api.vo.WebResult;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

@Data
public class BaseResponseDto extends BaseDto {
    private boolean success;
    private String errorCode;
    private String errorMsg;
    private static Logger logger = LoggerFactory.getLogger(WebResult.class);
    private Map<String, Object> data = new HashMap<>();


    public void clear() {
        data.clear();
        setSuccess(false);
        this.errorCode = null;
        setErrorMsg(null);
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
        if (errorCode != null) {
            put("errorCode", errorCode);
        }
    }

    public void setErrorCode(BaseErrorCode errorCode) {
        setSuccess(false);
        setErrorCode(errorCode.getCode());
        setErrorMsg(errorCode.getMsg());
    }


    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
        if (errorMsg != null) {
            put("errorMsg", errorMsg);
        }
    }

    public <E> E getData(String key, Class<E> clazz) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        Object data = get(key);
        try {

            String json = JsonUtil.toJson(data);
            return JsonUtil.readObject(json, clazz);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    public void put(String key, Object object) {
        data.put(key, object);
    }

    @SuppressWarnings("unchecked")
    public <T> T get(String key) {
        if (data.containsKey(key)) {
            return (T) data.get(key);
        } else {
            return null;
        }
    }

    public static BaseResponseDto getSuccessInstance() {
        BaseResponseDto baseResponseDto = new BaseResponseDto();
        baseResponseDto.setSuccess(true);
        return baseResponseDto;
    }

    public static BaseResponseDto getFailInstance(BaseErrorCode baseErrorCode) {
        BaseResponseDto baseResponseDto = new BaseResponseDto();
        baseResponseDto.setSuccess(false);
        baseResponseDto.setErrorCode(baseErrorCode);
        return baseResponseDto;
    }
}
